package net.shopxx.dao.impl;

import java.util.List;

import net.shopxx.bean.Pager;
import net.shopxx.dao.OrderPointerDao;
import net.shopxx.entity.Member;
import net.shopxx.entity.OrderPointer;
import net.shopxx.entity.Order.OrderStatus;
import net.shopxx.entity.Order.PaymentStatus;
import net.shopxx.entity.Order.ShippingStatus;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * Dao实现类 - 订单
 */

@Repository
public class OrderPointerDaoImpl extends BaseDaoImpl<OrderPointer, String> implements OrderPointerDao {
	
	@SuppressWarnings("unchecked")
	public String getLastOrderPointerSn() {
		String hql = "from OrderPointer as orderPointer order by orderPointer.createDate desc";
		List<OrderPointer> orderList =  getSession().createQuery(hql).setFirstResult(0).setMaxResults(1).list();
		if (orderList != null && orderList.size() > 0) {
			return orderList.get(0).getOrderSn();
		} else {
			return null;
		}
	}
	
	public Pager getOrderPointerPager(Member member, Pager pager) {
		if (pager == null) {
			pager = new Pager();
		}
		if (pager.getPageSize() == null) {
			pager.setPageSize(OrderPointer.DEFAULT_ORDER_LIST_PAGE_SIZE);
		}
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(OrderPointer.class);
		detachedCriteria.add(Restrictions.eq("member", member));
		return super.findByPager(pager, detachedCriteria);
	}
	
	public Long getUnprocessedOrderPointerCount() {
		String hql = "select count(*) from OrderPointer as orderPointer where orderPointer.orderStatus = ?";
		return (Long) getSession().createQuery(hql).setParameter(0, OrderStatus.unprocessed).uniqueResult();
	}
	
	public Long getPaidUnshippedOrderPointerCount() {
		String hql = "select count(*) from OrderPointer as orderPointer where orderPointer.paymentStatus = ? and orderPointer.shippingStatus = ? and orderPointer.orderStatus != ? and orderPointer.orderStatus != ?";
		return (Long) getSession().createQuery(hql).setParameter(0, PaymentStatus.paid).setParameter(1, ShippingStatus.unshipped).setParameter(2, OrderStatus.completed).setParameter(3, OrderStatus.invalid).uniqueResult();
	}
	
	
}